<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Goods;
use App\Image;


class GoodsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // dd($request);
        $goods = Goods::where(function($query) use ($request){
            //检测参数
            if(!empty($request->title)) {
                $query -> where('title','like','%'.$request->title.'%');
            }

            if(!empty($request->status)) {
                $query->where('status', $request->status);
            }

        })->orderBy('id','desc')->paginate($request->input('num',10));
        //读取用户的信息
        return view('admin.goods.index', ['goods'=>$goods,'request'=>$request]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.goods.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // var_dump($request->all());
        // 表单验证

        // 实例化对象
        $goods = new Goods;
        $goods->title = $request->title;
        $goods->price = $request->price;
        $goods->kucun = $request->kucun;
        $goods->size = implode('@@@', $request->size);
        $goods->color = implode('@@@', $request->color);
        $goods->detail = $request->detail;
        $goods->status = $request->status;

        if($goods->save()){
            $data = [];
           if($request->hasFile('img')){
                //上传图片
                foreach ($request->img as $key => $value) {
                    //检测文件是否可用
                    if($value->isValid()) {
                        //上传文件夹
                        $dirname = './Uploads/'.date('Ymd').'/';
                        //获取文件的后缀
                        $suffix = $value->getClientOriginalExtension();
                        //文件名
                        $name = time().rand(100000,999999).'.'.$suffix;

                        $value->move($dirname, $name); 

                        //获取图片路径
                        $src = trim($dirname.$name,'.');
                        
                        $image = new Image(['src'=>$src]);
                        $data[] = $image;
                    }
                }

                $res = $goods->image()->saveMany($data);

                if($res) {
                    return redirect('/goods')->with('success','添加成功');
                }else{
                    return back()->with('error','添加失败');
                }
            }
        }else{
            return back()->with('error','添加失败');
        }
    }

    /**
     * 商品详情
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $goods = Goods::where('kucun','>','0')->find($id);
        if(empty($goods))  abort(404);
        $related = Goods::take(4)->get();

        //解析模板
        return view('home.goods.detail', ['goods'=>$goods,'related'=>$related]);

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //读取商品的信息
        $good = Goods::findOrFail($id);

        //显示模板
        return view('admin.goods.edit', ['good'=>$good]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
         //实例化模型对象
        $goods = Goods::findOrFail($id);

        // dd($id);
        $goods->title = $request->title;
        $goods->price = $request->price;
        $goods->kucun = $request->kucun;
        $goods->size = implode('@@@', $request->size);
        $goods->color = implode('@@@', $request->color);
        $goods->detail = $request->detail;
        $goods->status = $request->status;

        
        if($goods->save()){
            $data = [];
           if($request->hasFile('img')){
                //上传图片
                foreach ($request->img as $key => $value) {
                    //检测文件是否可用
                    if($value->isValid()) {
                        //上传文件夹
                        $dirname = './Uploads/'.date('Ymd').'/';
                        //获取文件的后缀
                        $suffix = $value->getClientOriginalExtension();
                        //文件名
                        $name = time().rand(100000,999999).'.'.$suffix;

                        $value->move($dirname, $name); 

                        //获取图片路径
                        $src = trim($dirname.$name,'.');
                        
                        $image = new Image(['src'=>$src]);
                        $data[] = $image;
                    }
                }

                $res = $goods->image()->saveMany($data);

                if($res) {
                    return redirect('/goods')->with('success','添加成功');
                }else{
                    return back()->with('error','添加失败');
                }
            }
        }else{
            return back()->with('error','添加失败');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //获取数据
        $good = Goods::findOrFail($id);

        if($good->delete()){
            return back()->with('success','执行成功');
        }else{
            return back()->with('error','执行失败');
        }
    }

     /**
     * 商品信息采集.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function collection(Request $request)
    {
       // 获取页面源代码
        $code = file_get_contents('http://item.vancl.com/'.$request->path.".html");

        // 提取商品标题
        preg_match('/<title>(.*)- .* - VANCL 凡客诚品<\/title>/',$code,$title);
        // dd($title);
        // 提取商品图片
        preg_match_all('/<span class="SpriteSmallImgs" name="(.*)"/isU', $code, $images);
        // 提取大图
        $imgs = array_map(function($item){
            return str_replace('small', 'mid', $item);
        }, $images[1]);

       $images = [];
        foreach ($imgs as $key => $value) {
            $image = new Image(['src'=>$value]);
            $images[] = $image;
        }

        
        // dd($images);
        // 提取商品价格
        preg_match('/<strong>(.*)<\/strong><\/span><\/span>/',$code,$price);
        // dd($price);

        // 提取商品原价
        // preg_match("/<s>(.*)<\/s><\/span>/",$code,$cost);
        // dd($cost);
        

        // 提取商品详情
        preg_match('/<div id="testFloat1"><\/div>(.*)<map name="Map" id="Map">/isU', $code, $detail);

        // dd($detail);
        // 实例化对象模型
        $goods = new Goods;

        $goods->title = $title[1];
        $goods->price = rand(1500,2000);
        $goods->price = $price[1];
        $goods->detail = $detail[1];
        // $goods->grade = $grade[1]; 

        

        if($goods->save()){
            $goods->image()->saveMany($images);
            dd('添加成功');
        }else{
            dd('失败');
        }
    }
}
